package com.heima.media.intercept;

import com.heima.common.dto.User;
import com.heima.common.util.MediaThreadLocalUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserIntercept implements HandlerInterceptor {
    //前置拦截  在请求到达controller前拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求头中获取用户id
        String userId = request.getHeader("userId");
        //将用户信息放入到本地线程中
        if (!StringUtils.isEmpty(userId)) {
            User user = new User();
            user.setUserId(Integer.parseInt(userId));
            MediaThreadLocalUtil.set(user);
        }
        return true;
    }

    //在响应给前端之前拦截 例如修改用户的敏感数据
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //释放本地线程中的数据
        MediaThreadLocalUtil.remove();
    }
}
